package com.rachel.studyapp.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.client.android.BaseCaptureActivity;
import com.google.zxing.client.android.CusAutoScannerView;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.gyf.barlibrary.ImmersionBar;
import com.rachel.studyapp.R;
import com.rachel.studyapp.utils.BitmapUtils;
import com.rachel.studyapp.utils.ToolUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ScanZXingActivity extends BaseCaptureActivity implements View.OnClickListener {

    private static final String TAG = "zsr";
    /**
     * ui
     */
    private CusAutoScannerView mCusAutoScannerView;
    private SurfaceView mSurfaceView;
    private Button mPhoneBtn, mFlashBtn, mQrCideBtn;
    private boolean isFlash = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_zxing);
        mSurfaceView = (SurfaceView) findViewById(R.id.surface);
        mCusAutoScannerView = (CusAutoScannerView) findViewById(R.id.autoscanview);
        ImageView lefticon = (ImageView) findViewById(R.id.left_icon);
        lefticon.setVisibility(View.VISIBLE);
        lefticon.setImageResource(R.mipmap.back);
        lefticon.setOnClickListener(this);

        TextView textview = (TextView) findViewById(R.id.toolbar_text);
        textview.setVisibility(View.VISIBLE);
        textview.setText(getString(R.string.zxignscan));

        ToolUtils.setStatusBarColor(this,getResources().getColor(R.color.maincolor));

        // 底部
        mPhoneBtn = (Button) findViewById(R.id.photo_btn);
        mPhoneBtn.setOnClickListener(this);
        mFlashBtn = (Button) findViewById(R.id.flash_btn);
        mFlashBtn.setOnClickListener(this);
        mQrCideBtn = (Button) findViewById(R.id.qrcode_btn);
        mQrCideBtn.setOnClickListener(this);
        ImmersionBar.with(this).init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCusAutoScannerView.setCameraManager(cameraManager);
    }

    @Override
    public SurfaceView getSurfaceView() {
        return mSurfaceView == null? mSurfaceView =
                (SurfaceView) findViewById(R.id.autoscanview) : mSurfaceView;
    }

    @Override
    public void dealDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
        playBeepSoundAndVibrate();
        //Toast.makeText(this, "扫描到: "+rawResult.getText(), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.putExtra(ToolUtils.SCAN_RESULT,rawResult.getText());
        setResult(RESULT_OK,intent);
        finish();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.left_icon:
                finish();
                break;
            case R.id.photo_btn:
                BaseActivity.checkPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        new PermissionCallback() {
                            @Override
                            public void onGranted() {

                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                intent.setType("image/*");
                                startActivityForResult(intent,ToolUtils.SCAN_OPEN_PHONE);
                            }

                            @Override
                            public void onDenied(List<String> deniedPermissions) {
                                Toast.makeText(ScanZXingActivity.this, "打开失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                break;
            case R.id.flash_btn:
                isFlash = !isFlash;
                Log.d(TAG, "onClick: "+isFlash);
                if (isFlash){
                    mFlashBtn.setBackgroundResource(R.mipmap.scan_flash_icon_f);
                }else{
                    mFlashBtn.setBackgroundResource(R.mipmap.scan_flash_icon);
                }
                //ToolUtils.openFlash(ScanZXingActivity.this,isFlash);
                cameraManager.setTorch(isFlash);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == ToolUtils.SCAN_OPEN_PHONE){
                new BitmapDecodeSync(data).execute();
            }
        }
    }

    class BitmapDecodeSync extends AsyncTask<Void,Void,String>{
        Intent data;

        public BitmapDecodeSync(Intent data) {
            this.data = data;
        }

        @Override
        protected String doInBackground(Void... params) {
            String path = BitmapUtils.UriTranslationPath(ScanZXingActivity.this,data.getData());
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            if (bitmap != null) {
                String result = decode(bitmap);
                return result;
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                Intent intent = new Intent();
                intent.putExtra(ToolUtils.SCAN_RESULT, result);
                setResult(RESULT_OK, intent);
                playBeepSoundAndVibrate();
                finish();
            }else{
                Toast.makeText(ScanZXingActivity.this, "图片解析失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 解析Bitmap中的二维码
     *
     * @param bitmap
     * @return 解析结果，null表示解析失败
     */
    private String decode(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        final int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        RGBLuminanceSource luminanceSource = new RGBLuminanceSource(width, height, pixels);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

        try {
            final Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
            hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            Result result = new QRCodeReader().decode(binaryBitmap, hints);

            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }




}
